package com.basics.framework.web.domain;

import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class AjaxResult extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    public AjaxResult() {
    }

    public static AjaxResult error() {
        return error(1, "操作失败");
    }

    public static AjaxResult error(String msg) {
        return error(500, msg);
    }

    public static AjaxResult errorToken() {
        return error(2, "token失效");
    }

    public static AjaxResult error(int code, String msg) {
        AjaxResult json = new AjaxResult();
        json.put((String)"code", code);
        json.put((String)"msg", msg);
        return json;
    }

    public static AjaxResult success(String msg) {
        AjaxResult json = new AjaxResult();
        json.put((String)"msg", msg);
        json.put((String)"code", 0);
        return json;
    }

    public static AjaxResult success() {
        return success("操作成功");
    }

    public AjaxResult put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public AjaxResult onBindingError(List<ObjectError> errors) {
        AjaxResult json = new AjaxResult();
        json.put((String)"code", 500);
        json.put((String)"msg", praseErrorMessage(errors));
        return json;
    }

    public static String praseErrorMessage(List<ObjectError> errors) {
        StringBuffer stringBuffer = new StringBuffer();
        Iterator var2 = errors.iterator();

        while(var2.hasNext()) {
            ObjectError error = (ObjectError)var2.next();
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError)error;
                stringBuffer.append(fieldError.getDefaultMessage());
                stringBuffer.append(",");
            }
        }

        return stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
    }
}
